<template>
  <div class="app-container">
    <el-form
      class="filters"
      ref="searchForm"
      :model="searchForm"
      label-width="90px"
    >
      <el-form-item label="菜单名称">
        <el-input v-model="searchForm.name" clearable placeholder="请输入菜单名称" />
      </el-form-item>
      <div class="search-btns">
        <el-button
          type="primary"
          size="mini"
          icon="el-icon-search"
          @click="fetchData"
          >搜索</el-button
        >
        <el-button
          type="default"
          size="mini"
          icon="el-icon-refresh"
          @click="resetSearch"
          >重置</el-button
        >
      </div>
    </el-form>
    <div class="searchs-content">
      <el-button
        type="primary"
        size="mini"
        plain
        icon="el-icon-plus"
        @click="handleEdit({}, 1)"
        >新增</el-button
      >
      <el-button
        type="success"
        size="mini"
        plain
        :icon="isExpansion ? 'el-icon-arrow-up' : 'el-icon-arrow-down'"
        @click="toggleRowExpansion"
        >展开/折叠</el-button
      >
    </div>
    <el-table
      :data="tableData"
      row-key="id"
      border
      :expand-row-keys="expandKeys"
      ref="dataTreeList" @expand-change="expandChange"
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
    >
      <el-table-column prop="name" label="菜单名称"> </el-table-column>
      <el-table-column prop="orderNum" label="排序" width="70" align="center"> </el-table-column>
      <el-table-column prop="type" label="类型" width="100" align="center">
        <!-- （M(1)目录 C(2)菜单 F(3)按钮） -->
        <template slot-scope="scope">
          <el-tag effect="dark" size="mini" v-if="scope.row.type == 'M'"
            >目录</el-tag
          >
          <el-tag
            effect="dark"
            size="mini"
            type="success"
            v-else-if="scope.row.type == 'C'"
            >菜单</el-tag
          >
          <el-tag
            effect="dark"
            size="mini"
            type="warning"
            v-else-if="scope.row.type == 'F'"
            >按钮</el-tag
          >
        </template>
      </el-table-column>
      <!-- <el-table-column prop="isVisible" label="可见">
        <template slot-scope="scope">
          <el-tag effect="dark" size="mini" v-if="scope.row.isVisible == 0"
            >显示</el-tag
          >
          <el-tag
            effect="dark"
            size="mini"
            type="warning"
            v-else-if="scope.row.isVisible == 1"
            >隐藏</el-tag
          >
        </template>
      </el-table-column> -->
      <el-table-column prop="orderNum" label="所属平台" width="120" align="center">
        <template slot-scope="scope">
          <span>{{ platFormType(scope.row.platformType) }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="orderNum" label="设备分类" align="center">
        <template slot-scope="scope">
          <span v-if="scope.row.applyEquipClassifyList">{{ scope.row.applyEquipClassifyList.join('，') }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="perms" label="权限标识" align="center"> </el-table-column>
      <el-table-column label="操作" align="center">
        <template slot-scope="scope">
          <!-- 按钮级不允许新增 -->
          <el-button
            v-if="scope.row.type == 'M' || scope.row.type == 'C'"
            size="mini"
            type="primary"
            @click="handleEdit(scope.row, 1)"
            >新增</el-button
          >
          <el-button
            size="mini"
            type="success"
            @click="handleEdit(scope.row, 2)"
            >编辑</el-button
          >
          <el-button size="mini" type="danger" @click="handleDelete(scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <!-- 弹框 -->
    <Dialog
      :visible="visible"
      width="40%"
      :loading="dialogBtnLoading"
      :title="dialogTitle"
      @confirmDialog="confirmDialog"
      @cancelDialog="cancelDialog"
    >
      <el-form
        ref="dialogForm"
        :model="dialogForm"
        label-width="120px"
        :rules="dialogRules" size="small"
      >
        <el-form-item label="上级菜单：">
          <el-cascader clearable
            ref="parentCascader"
            :value="editshowvalue"
            :options="lastMenuData"
            :props="{ value: 'id', label: 'name', checkStrictly: true }"
            :show-all-levels="false"
            @change="cascaderChange($event)"
          ></el-cascader>
        </el-form-item>
        <el-form-item label="菜单类型：" prop="type">
          <el-radio-group v-model="dialogForm.type" @change="radioChange">
            <el-radio
              v-for="(radio, inx) in menuType"
              :label="radio.code"
              :key="inx"
              :disabled="radio.disabled"
              >{{ radio.label }}</el-radio
            >
          </el-radio-group>
        </el-form-item>
        <el-form-item label="菜单名称：" prop="name">
          <el-input clearable
            v-model="dialogForm.name"
            placeholder="请输入菜单名称"
          ></el-input>
        </el-form-item>

        <el-form-item label="所属平台：" prop="platformType">
          <el-select v-model="dialogForm.platformType" placeholder="请选择所属平台" clearable>
            <el-option
              v-for="item in enums.PLATFORM_TYPE"
              :key="item.code"
              :label="item.label"
              :value="item.code">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="设备分类：" prop="applyEquipClassifys">
          <el-select v-model="dialogForm.applyEquipClassifys" multiple placeholder="请选择设备分类" clearable>
            <el-option
              v-for="item in enums.EQUIP_CLASSIFY"
              :key="item.code"
              :label="item.label"
              :value="item.code">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="权限标识：">
          <el-input v-model="dialogForm.perms" clearable></el-input>
        </el-form-item>
        <el-form-item label="英文名称：">
          <el-input v-model="dialogForm.enName" clearable></el-input>
        </el-form-item>
        <el-form-item label="显示排序：" prop="orderNum">
          <el-input-number
            controls-position="right"
            v-model="dialogForm.orderNum"
            :min="0"
          ></el-input-number>
        </el-form-item>
        <el-form-item label="是否系统内置：" prop="isInner">
          <el-radio-group v-model="dialogForm.isInner">
            <el-radio
              v-for="(radio, inx) in enums.IS_SYSTEM"
              :label="radio.code"
              :key="inx"
              >{{ radio.label }}</el-radio
            >
          </el-radio-group>
        </el-form-item>
        <!-- <el-form-item
          label="菜单状态："
          prop="isVisible"
        >
          <el-radio-group v-model="dialogForm.isVisible">
            <el-radio
              v-for="(radio, inx) in menuStatus"
              :label="radio.code"
              :key="inx"
              >{{ radio.label }}</el-radio
            >
          </el-radio-group>
        </el-form-item> -->
      </el-form>
    </Dialog>
  </div>
</template>

<script>
import { getMenu } from "@/api/user";
import Dialog from "@/components/Dialog";

import { handleConfirm } from "@/utils/messageBox";
import { removeNullUndefined } from "@/utils/index.js";
import { menuType, menuStatus } from "@/utils/config";
import { mapGetters } from "vuex";

export default {
  components: { Dialog },
  data() {
    return {
      listLoading: true,
      searchForm: {
        name: "",
      },

      tableData: [],
      visible: false, //弹框标识
      dialogForm: {
        parentId: "",
        type: "",
        name: "",
        perms: "",
        orderNum: null,
        isInner: null,
        enName: "",
        platformType:"",//所属平台
        applyEquipClassifys:[],//设备分类
      },
      dialogRules: {
        type: [
          { required: true, message: "请选择菜单类型", trigger: "change" },
        ],
        name: [{ required: true, message: "请输入菜单名称", trigger: "blur" }],
        orderNum: [
          { required: true, message: "请输入显示排序", trigger: "blur" },
        ],
        platformType: [
          { required: true, message: "请选择所属平台", trigger: "change" },
        ],
        applyEquipClassifys: [
          { required: true, message: "请选择设备分类", trigger: "change" },
        ],
      },
      dialogTitle: "",
      dialogBtnLoading: false,
      menuType: menuType, //菜单类型
      menuStatus: menuStatus, //菜单状态
      lastMenuData: [], //上级菜单
      curMenuType: "C", //当前选中菜单类型
      isExpansion: false,
      editshowvalue: null,
      expandKeys: [], //展开项
    };
  },
  computed: {
    ...mapGetters(["enums"]),
  },
  filters: {},
  created() {
    this.fetchData();
  },
  methods: {
    fetchData() {
      this.listLoading = true;
      this.tableData = [];
      getMenu("/list", { ...removeNullUndefined(this.searchForm) })
        .then((res) => {
          this.tableData = res.data;
        })
        .finally(() => {
          this.listLoading = false;
        });
    },
    // 弹框取消
    cancelDialog() {
      this.visible = false;
      this.dialogForm = {
        parentId: "",
        type: "",
        name: "",
        perms: "",
        orderNum: null,
        isInner: null,
        enName: "",
        applyEquipClassifys:"",
        platformType:"",
      };
      this.editshowvalue = null;
      this.$refs['dialogForm'].resetFields();
    },
    // 弹框确认
    confirmDialog() {
      this.submitDialogForm("dialogForm");
    },
    // 新增/编辑
    handleEdit(row, type) {
      // type:1,新增；2，编辑
      this.visible = true;
      this.$nextTick(() => {
        this.$refs.dialogForm.clearValidate()
      })

      this.getUserMenu();
      
      if (type == 2) {
        this.dialogTitle = "编辑";
        
        row.applyEquipClassifys = typeof row.applyEquipClassifys === 'string'? row.applyEquipClassifys.split(','):row.applyEquipClassifys;
        let { id, name, parentId, type, perms, orderNum, isInner, enName ,platformType,applyEquipClassifys} =
          row;
        this.dialogForm = {
          id,
          name,
          parentId,
          type,
          perms,
          orderNum,
          isInner,
          enName,platformType,applyEquipClassifys
        };
        this.editshowvalue = parentId;
      } else {
        this.dialogTitle = "新增";
        if (row.id) {
          this.dialogForm.parentId = row.id;
          this.editshowvalue = row.id;

          this.dialogForm.applyEquipClassifys = typeof row.applyEquipClassifys === 'string'? row.applyEquipClassifys.split(','):row.applyEquipClassifys;
          this.dialogForm.platformType = row.platformType;
        }
      }

      if (this.dialogForm.parentId && this.dialogForm.parentId != "0") {
        this.menuType.forEach((item) => {
          item.disabled = true;
        });
        // 上级菜单是目录时，当前允许增加菜单类型；
        // 上级菜单是菜单时，当前允许增加按钮
        if (type == 1) {
          switch (row.type) {
            case "M":
              this.menuType[1].disabled = false;
              break;
            case "C":
              this.menuType[2].disabled = false;
              break;
          }
        } else {
          switch (row.type) {
            case "C":
              this.menuType[1].disabled = false;
              break;
            case "F":
              this.menuType[2].disabled = false;
              break;
          }
        }
      } else {
        this.menuType.forEach((item) => {
          item.disabled = false;
        });
      }
    },
    // 获取用户菜单权限
    async getUserMenu() {
      const menus = await getMenu(`/list`);
      this.lastMenuData = this.filterTreeData(menus.data);
    },
    filterTreeData(arr) {
      const newArr = arr.filter((item) => item.type != "F");
      return newArr.map((item) => {
        if (
          item.children.length > 0 &&
          item.children.filter((p) => p.type != "F").length > 0
        ) {
          item.children = this.filterTreeData(item.children);
        } else {
          item.children = undefined;
        }
        return item;
      });
    },
    submitDialogForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let msg = this.dialogForm.id ? "编辑" : "新增";
          handleConfirm(`确定要${msg}吗？`, "warning", "提示")
            .then((res) => {
              this.doOperate();
            })
            .catch((err) => {});
        } else {
          return false;
        }
      });
    },
    resetDialogForm(formName) {
      this.$refs[formName].resetFields();
    },

    resetSearch() {
      this.searchForm = {
        name: "",
      };
    },

    doOperate() {
      this.dialogBtnLoading = true;
      let url = this.dialogForm.id ? "/update" : "/insert";
      let params = Object.assign({},this.dialogForm);
      params.applyEquipClassifys= params.applyEquipClassifys.join(',');
      getMenu(url, { ...removeNullUndefined(params) }, "post", 1)
        .then((res) => {
          if (res.code == 200) {
            this.$message.success(res.message);
            this.visible = false;
            this.fetchData();
          }
        })
        .finally(() => {
          this.dialogBtnLoading = false;
        });
    },
    // 删除
    handleDelete(row) {
      handleConfirm("删除后不可恢复，确定继续？", "warning", "提示")
        .then((res) => {
          this.doDelete(row);
        })
        .catch((err) => {});
    },
    doDelete(row) {
      getMenu(`/delete/${row.id}`, {}, "delete").then((res) => {
        if (res.code == 200) {
          this.$message.success(res.message);
          this.fetchData();
        }
      });
    },
    // 菜单类型change
    radioChange(e) {
      this.curMenuType = e;
    },
    cascaderChange($event) {
      this.dialogForm.type = "";
      this.dialogForm.parentId = $event[$event.length - 1];

      let nodes = this.$refs["parentCascader"].getCheckedNodes();
      let type = nodes[0].data.type;
      this.menuType.forEach((item) => {
        item.disabled = true;
      });
      // 上级菜单是目录时，当前允许增加菜单类型；
      // 上级菜单是菜单时，当前允许增加按钮
      switch (type) {
        case "M":
          this.menuType[1].disabled = false;
          break;
        case "C":
          this.menuType[2].disabled = false;
          break;
      }
    },
    // 切换数据表格树形展开
    toggleRowExpansion() {
      this.isExpansion = !this.isExpansion;
      this.toggleRowExpansionAll(this.tableData, this.isExpansion);
    },
    toggleRowExpansionAll(data, isExpansion) {
      data.forEach((item) => {
        this.$refs.dataTreeList.toggleRowExpansion(item, isExpansion);
        if (item.children !== undefined && item.children !== null) {
          this.toggleRowExpansionAll(item.children, isExpansion);
        }
      });
    },
    platFormType(type) {
      let classify = this.enums.PLATFORM_TYPE.find((p) => {
        return p.code == type;
      });
      return classify ? classify.label : "";
    },
    expandChange(row,expandedRows){
      if(expandedRows){//展开
        this.expandKeys.push(row.id);
      }
      else{//收起
        this.expandKeys.splice(this.expandKeys.indexOf(row.id), 1);
      }
    },

  },
};
</script>
<style lang="scss" scoped>
::v-deep .el-cascader,.el-input,.el-select,
::v-deep .el-input-number {
  width: 96%;
}
</style>
